package com.ruoyi.service.impl;

import java.util.*;

import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.domain.ParkingInfo;
import com.ruoyi.mapper.ParkingInfoMapper;
import com.ruoyi.wss.WebSocketMessageService;
import com.ruoyi.wss.dahua.Enum.MasWebsocketEnum;
import com.ruoyi.wss.dahua.config.DaHuaConfig;
import com.ruoyi.wss.dahua.request.CommonRequest;
import com.ruoyi.wss.dahua.request.MemberCardListRequest;
import com.ruoyi.wss.dahua.request.MemberCardRequest;
import com.ruoyi.wss.dahua.request.RequestData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.mapper.ParkingCardMapper;
import com.ruoyi.domain.ParkingCard;
import com.ruoyi.service.IParkingCardService;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;

/**
 * 停车卡Service业务层处理
 * 
 * @author dongdong
 * @date 2025-09-09
 */
@Slf4j
@Service
public class ParkingCardServiceImpl implements IParkingCardService 
{
    @Resource
    private ParkingCardMapper parkingCardMapper;
    @Resource
    private ParkingInfoMapper parkingInfoMapper;
    @Autowired
    private WebSocketMessageService webSocketMessageService;
    @Autowired
    private TransactionTemplate transactionTemplate;

    /**
     * 查询停车卡
     * 
     * @param id 停车卡主键
     * @return 停车卡
     */
    @Override
    public ParkingCard selectParkingCardById(Long id)
    {
        return parkingCardMapper.selectParkingCardById(id);
    }

    /**
     * 查询停车卡列表
     * 
     * @param parkingCard 停车卡
     * @return 停车卡
     */
    @Override
    @DataScope(deptAlias = "pc")
    public List<ParkingCard> selectParkingCardList(ParkingCard parkingCard)
    {
        return parkingCardMapper.selectParkingCardList(parkingCard);
    }

    /**
     * 新增停车卡
     * 
     * @param parkingCard 停车卡
     * @return 结果
     */
    @Override
    public int insertParkingCard(ParkingCard parkingCard)
    {
        ParkingInfo parkingInfo = parkingInfoMapper.selectParkingInfoById(parkingCard.getParkId());
        if (Objects.isNull(parkingInfo)){
            throw new RuntimeException("未查询到停车场信息");
        }
        Date dateTime = DateUtils.getNowDate();
        parkingCard.setCreateTime(dateTime);
        parkingCard.setUpdateTime(dateTime);
        parkingCard.setChannel(3);
        parkingCard.setDeptId(parkingInfo.getDeptId());
        Boolean execute = transactionTemplate.execute(e -> {
            parkingCardMapper.insertParkingCard(parkingCard);
            return sendMemberCardRequest(DaHuaConfig.MEMBER_CARD_ADD, parkingCard, parkingInfo);
        });
        if (!execute){
            throw new RuntimeException("停车卡下发失败");
        }
        return 1;

    }

    /**
     * 修改停车卡
     * 
     * @param parkingCard 停车卡
     * @return 结果
     */
    @Override
    public int updateParkingCard(ParkingCard parkingCard) {
        ParkingInfo parkingInfo = parkingInfoMapper.selectParkingInfoById(parkingCard.getParkId());
        if (Objects.isNull(parkingInfo)){
            throw new RuntimeException("未查询到停车场信息");
        }
        parkingCard.setUpdateTime(DateUtils.getNowDate());
        Boolean execute = transactionTemplate.execute(e -> {
            parkingCardMapper.updateParkingCard(parkingCard);
            return sendMemberCardRequest(DaHuaConfig.MEMBER_CARD_UPDATE, parkingCard, parkingInfo);
        });
        if (!execute){
            throw new RuntimeException("停车卡下发失败");
        }
        return 1;
    }

    /**
     * 批量删除停车卡
     * 
     * @param ids 需要删除的停车卡主键
     * @return 结果
     */
    @Override
    public int deleteParkingCardByIds(Long[] ids)
    {
        return parkingCardMapper.deleteParkingCardByIds(ids);
    }

    /**
     * 删除会员卡信息
     * 大华下级平台，没有提供删除会员卡和月卡下发删除的指令，只有修改有效期的指令
     * 当删除会员卡时，把有效期修改为过期
     * @param id 会员卡主键
     * @return 结果
     */
    @Override
    public int deleteParkingCardById(Long id) {
        ParkingCard parkingCard = parkingCardMapper.selectParkingCardById(id);
        Optional.ofNullable(parkingCard).orElseThrow(() -> new RuntimeException("无效的请求数据"));
        ParkingInfo parkingInfo = parkingInfoMapper.selectParkingInfoById(parkingCard.getParkId());
        if (Objects.isNull(parkingInfo)){
            throw new RuntimeException("未查询到停车场信息");
        }
        parkingCard.setUpdateTime(DateUtils.getNowDate());
        Date date = DateUtils.getYesterdayDate();
        parkingCard.setValidStartTime(date);
        parkingCard.setValidEndTime(date);
        Boolean execute = transactionTemplate.execute(e -> {
            Boolean res = sendMemberCardRequest(DaHuaConfig.MEMBER_CARD_UPDATE, parkingCard, parkingInfo);
            parkingCardMapper.deleteParkingCardById(id);
            return res;
        });
        if (!execute){
            throw new RuntimeException("停车卡下发失败");
        }
        return 1;
    }


    /**
     * 按照下级平台ID 拆分所属停车场
     * @param operateType
     * @param parkingCard
     * @return
     */
    public Boolean sendMemberCardRequest(Integer operateType, ParkingCard parkingCard, ParkingInfo parkingInfo){
        log.info("停车卡下发JSON：{}", parkingCard);
        String platformId = parkingInfo.getPlatformId();
        // 组装请求参数
        MemberCardRequest memberCardRequest = MemberCardRequest.builder()
                .cloudRecordId(String.valueOf(parkingCard.getId()))
                .carNum(parkingCard.getCarNum())
                .carNumColor(parkingCard.getCarNumColor().intValue())
                .money(parkingCard.getAmount())
                .owner(parkingCard.getOwner())
                .ownerTel(parkingCard.getOwnerTel())
                .parkingLotCodes(parkingInfo.getParkCode())
                .operateType(operateType)
                .validStartTimeStr(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, parkingCard.getValidStartTime()))
                .validEndTimeStr(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, parkingCard.getValidEndTime()))
                .operateTimeStr(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, parkingCard.getUpdateTime()))
                .build();
        List<MemberCardRequest> list = new ArrayList<>();
        list.add(memberCardRequest);

        MemberCardListRequest memberCardList = new MemberCardListRequest();
        memberCardList.setPlatformId(platformId);
        memberCardList.setData(list);

        // 发送请求
        RequestData<MemberCardListRequest> requestData = new RequestData<>(
                MasWebsocketEnum.MEMBER_SYNC_INCREMENT.getMethod(), memberCardList);
        CommonRequest<MemberCardListRequest> cardRequest = new CommonRequest<>("transform", 1, requestData);
        log.info("停车卡下发请求JSON：{}", memberCardRequest);
        try {
            Boolean result = webSocketMessageService.operationDevice(platformId, cardRequest);
            if(!result){
                throw new RuntimeException("停车卡下发失败");
            }
        } catch (Exception ex) {
            log.error("停车卡下发失败：{}，下级平台：{}", ex.getMessage(), platformId);
            throw new RuntimeException("停车卡下发失败");
        }
        return Boolean.TRUE;
    }
}
